package com.bac.rentmap.ad.crawler.jdo;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.bac.rentmap.ad.crawler.AdCrawler;
import com.bac.rentmap.ad.crawler.Context;
import com.bac.rentmap.ad.crawler.CrawledAd;
import com.bac.rentmap.ad.flat.jdo.JdoFlatAdDao;
import com.bac.rentmap.jdo.JdoSupport;

/**
 * Delegates crawling to <code>adCrawler</code> and stores it's crawling result
 * using JDO. Storing is performed in reverse order.
 * 
 * @author Andrew Osipenko
 * 
 * @param <T>
 *            type used to store crawled data
 */
public class JdoPersistingAdCrawler<T extends CrawledAd> extends JdoSupport
		implements AdCrawler<T> {
	private static final Logger log = Logger.getLogger(JdoFlatAdDao.class
			.getName());

	private AdCrawler<T> adCrawler;

	public JdoPersistingAdCrawler(AdCrawler<T> adCrawler) {
		this.adCrawler = adCrawler;
	}

	public List<T> crawl(Context context) throws IOException {
		List<T> crawledAds = adCrawler.crawl(context);
		Collections.reverse(crawledAds);
		PersistenceManager persistenceManager = getPersistenceManager();
		try {
			log.info("Persisting " + crawledAds.size() + " ads");
			persistenceManager.makePersistentAll(crawledAds);
		} finally {
			persistenceManager.close();
		}
		return crawledAds;
	}

}
